package cn.antblog.ip;

import java.net.*;
import java.util.Enumeration;

public class IpUtils {

    private static final String[] ADDR_HEADER = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
            "X-Real-IP" };
    private static final String NUKNOWN = "unknown";

    public static void main(String[] args) throws UnknownHostException {
        getLocalHostLANAddress();
    }

    // 正确的IP拿法，即优先拿site-local地址
    private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        String hostAddress = inetAddr.getHostAddress();
                        boolean linkLocalAddress = inetAddr.isLinkLocalAddress();
                        boolean anyLocalAddress = inetAddr.isAnyLocalAddress();
                        boolean mcGlobal = inetAddr.isMCGlobal();
                        boolean mcLinkLocal = inetAddr.isMCLinkLocal();
                        boolean mcNodeLocal = inetAddr.isMCNodeLocal();
                        boolean mcOrgLocal = inetAddr.isMCOrgLocal();
                        boolean mcSiteLocal = inetAddr.isMCSiteLocal();
                        boolean multicastAddress = inetAddr.isMulticastAddress();

                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了

                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                String hostAddress = candidateAddress.getHostAddress();
                byte[] address = candidateAddress.getAddress();
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            throw unknownHostException;
        }
    }







}
